package redis

import (
	"enjoy_wangyashuo/formdata/types"
	"errors"
	"fmt"
	"github.com/go-redis/redis"
	"github.com/spf13/viper"
	"time"
)

func RedisClient(hand func(rdb *redis.Client) error) error {
	config := types.ViperData
	err := viper.Unmarshal(&config)
	if err != nil {
		return err
	}
	addr := fmt.Sprintf("%s:%d", config.Redis.Host, config.Redis.Port)
	client := redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: config.Redis.Password, // no password set
		DB:       0,                     // use default DB
	})
	defer client.Close()
	pong, err := client.Ping().Result()
	fmt.Println(pong, err)
	return hand(client)

}

// 获取redis值
func GetRedisVal(key string) (val *redis.StringCmd, err error) {
	fmt.Println("Fetching Redis Key:", key) // 打印要获取的 Redis 键名
	return val, RedisClient(func(rdb *redis.Client) error {
		val = rdb.Get(key)
		if val.Err() != nil {
			fmt.Println("Redis Get Error:", val.Err()) // 打印 Redis 获取错误
		}
		return nil
	})
}

// 储存redis
func SetRedisVal(key string, val string, times time.Duration) error {
	return RedisClient(func(rdb *redis.Client) error {
		err := rdb.Set(key, val, times).Err()
		if err != nil {
			return errors.New("redis set error: " + err.Error())
		}
		return nil
	})
}
